package com.diandian.client;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

/**
 * Description of UdpClient
 * Copyright 2017 Meorient, Inc. All rights reserved.
 *
 * @author yuancheng.li on 2018年03月22日
 */
public class UdpClient {

    private final static int PORT = 1234;

    private static final int BYTE_LEN = 1024;

    private final static String IP = "127.0.0.1";

    public static void main(String[] args) throws IOException {
        new UdpClient().init();
    }

    public void init() throws IOException {

        byte[] readBuffer = new byte[BYTE_LEN];

        DatagramSocket socket = new DatagramSocket();
        InetAddress inetAddress = InetAddress.getByName(IP);

        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {

            String read = scanner.nextLine();
            if (read == null || read.length() == 0 || read.equals("exist")) {
                break;
            }

            byte[] bytes = read.getBytes();
            DatagramPacket packet = new DatagramPacket(bytes, bytes.length, inetAddress, PORT);
            socket.send(packet);

            DatagramPacket inPacket = new DatagramPacket(readBuffer, BYTE_LEN);
            socket.receive(inPacket);
            byte[] data = inPacket.getData();
            System.out.println("received msg=>" + new String(data, 0, inPacket.getLength()));
        }


    }

}
